package main

import (
	"flag"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"myCloud/config"
	"myCloud/dbmodel"
	"myCloud/dbopr"
	"myCloud/logsvr"
	"myCloud/notify"
	"myCloud/thumb"
	"myCloud/webv1"
	"time"
)

var (
	logger = logsvr.GetLogger("main")

	// flag
	addUser = flag.Bool("a", false, "add default user")
)

/*
1，初始化配置
2，初始化数据库
4，初始化web服务器等
5，mDNS初始化
*/
func main() {
	rand.Seed(time.Now().Unix())
	flag.Parse()

	cfg, err := config.LoadConfig("./config.json")
	if err != nil {
		fmt.Printf("read config failed, %s\n", err.Error())
		return
	}

	err = dbopr.DatabaseInit(cfg.Database)
	if err != nil {
		fmt.Printf("init db failed, %s\n", err.Error())
		return
	}

	logsvr.LogInit(cfg.Logging.FileName, cfg.Logging.Level)

	if addUser != nil && *addUser == true {
		addDefaultUser()
		return
	}

	// 加载设备ID
	p := dbopr.NewServerProvider()
	info, err := p.Init(serverIdGenerator)
	if err != nil {
		fmt.Printf("init server failed, %s\n", err)
		return
	}

	logger.Info(fmt.Sprintf("server %s completed", info.ServerID))
	notify.SvrInit(cfg.Mq)
	go thumb.SvrInit("./thumb.db", cfg.Mq.Path)
	//go publishService(info.ServerID)

	webv1.ApiServerV2()
}

func addDefaultUser() {
	u := &dbmodel.User{
		Role:     "",
		UserName: "esync",
		NickName: "esync",
		Stat:     "VALID",
	}
	u.EncodePassword("123456")
	p := dbopr.NewUserProvider()
	err := p.New(u)
	if err != nil {
		println("new user failed", err)
		return
	}
}

func serverIdGenerator() string {
	u := uuid.New()
	return u.String()
}

//go:generate esc -pkg embed -o ../../embed/resource.go ../../../portal

